package com.chen.apidriver.service;

import com.chen.apidriver.remote.ServiceDriverUserClient;
import com.chen.apidriver.remote.ServiceVerificationCodeClient;
import com.chen.internalcommon.constant.CommonStatusEnum;
import com.chen.internalcommon.constant.DriverCarConstants;
import com.chen.internalcommon.constant.IdentityConstants;
import com.chen.internalcommon.dto.ResponseResult;
import com.chen.internalcommon.response.DriverUserExistsResponse;
import com.chen.internalcommon.response.NumberCodeResponse;
import com.chen.internalcommon.response.TokenResponse;
import com.chen.internalcommon.util.JwtUtils;
import com.chen.internalcommon.util.RedisPrefixUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @author chenLiuPing
 **/
@Service
@Slf4j
public class VerificationCodeService {

    @Autowired
    private ServiceDriverUserClient serviceDriverUserClient;

    @Autowired
    private ServiceVerificationCodeClient serviceVerificationCodeClient;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public ResponseResult checkAndSendVerificationCode(String driverPhone) {
        // 调用service-driver-user 服务 查询driverPhone对应的司机是否存在
        ResponseResult<DriverUserExistsResponse> driverUserExists = serviceDriverUserClient.getUser(driverPhone);
        int ifExists = driverUserExists.getData().getIfExists();
        if (ifExists == DriverCarConstants.DRIVER_NOT_EXISTS) {
            log.info("手机号{}对应司机信息不存在", driverPhone);
            return ResponseResult.fail(CommonStatusEnum.DRIVER_NOT_EXISTS);
        }
        log.info("司机信息存在");
        // 调用验证码服务获取验证码
        ResponseResult<NumberCodeResponse> numberCodeResponse = serviceVerificationCodeClient.getNumberCode(6);
        int numberCode = numberCodeResponse.getData().getNumberCode();
        log.info("获取到的验证码：{}", numberCode);

        // 调用第三方短信服务 发送验证码
        log.info("调用第三方服务发送验证码");
        // 验证码存入redis
        String key = RedisPrefixUtils.generateCodeKeyByPhone(driverPhone, IdentityConstants.DRIVER_IDENTITY);
        stringRedisTemplate.opsForValue().set(key, String.valueOf(numberCode), 2, TimeUnit.MINUTES);
        log.info("验证码存入redis");
        return ResponseResult.success();
    }

    /**
     * 校验验证码
     * @param driverPhone
     * @param verificationCode
     * @return
     */
    public ResponseResult checkCode(String driverPhone, String verificationCode) {
        // 根据手机号去redis查询验证码
        String codeKey = RedisPrefixUtils.generateCodeKeyByPhone(driverPhone, IdentityConstants.DRIVER_IDENTITY);
        String redisCode = stringRedisTemplate.opsForValue().get(codeKey);
        // 根据redis查询到的验证码进行校验
        if (!Objects.equals(verificationCode, redisCode)) {
            log.info("验证码错误");
            return ResponseResult.fail(CommonStatusEnum.VERIFICATION_CODE_ERROR);
        }
        log.info("验证码正确");
        // TODO 验证码正确之后需要删除验证码么 ？
        // 获取双token
        String accessTokenKey = RedisPrefixUtils.generateAccessTokenKey(driverPhone, IdentityConstants.DRIVER_IDENTITY);
        String accessToken = JwtUtils.generateAccessToken(driverPhone, IdentityConstants.DRIVER_IDENTITY);
        String refreshTokenKey = RedisPrefixUtils.generateRefreshTokenKey(driverPhone, IdentityConstants.DRIVER_IDENTITY);
        String refreshToken = JwtUtils.generateRefreshToken(driverPhone, IdentityConstants.DRIVER_IDENTITY);
        // 双token存入redis
        stringRedisTemplate.opsForValue().set(accessTokenKey, accessToken, 30,  TimeUnit.DAYS );
        stringRedisTemplate.opsForValue().set(refreshTokenKey, refreshToken, 31, TimeUnit.DAYS);
        log.info("生成的双token已存入redis");
        // 返回双token
        TokenResponse tokenResponse = new TokenResponse(accessToken, refreshToken);
        return ResponseResult.success(tokenResponse);
    }
}
